import qs from 'qs'
import axios from 'axios'

class Request {
  constructor(options) {
    const { APIURL = 'https://www.icu007.top' } = options
    this.options = options
    this.instance = axios.create(options)
    this.instance.defaults.baseURL = `${APIURL}`
    this.init()
  }

  _requestIntercepter(config) {
    // console.log(11, config)
    if (config.params) { //
      config.params.model = 'gpt-3.5-turbo'
    } else {
      config.data = {
        ...config.data,
        model: 'gpt-3.5-turbo',
        stream: true
      }
      // config.data = qs.stringify(config.data)
    }
    console.log('loading...')
    return config
  }

  _responseIntercepter(response) {
    console.log('loading end', response)
    if (response.status !== 200) {
      console.log(`${response.status} - ${response.statusText}`)
      return Promise.reject(response)
    }

    return response.data
  }

  init() {
    this.instance.interceptors.request.use(this._requestIntercepter, error => Promise.reject(error))

    this.instance.interceptors.response.use(this._responseIntercepter, error => {
      console.log('loading end')
      console.log('网络连接失败');
      return Promise.reject(error)
    })
  }

  request(config, options) {
    if (undefined === config.method || config.method.toUpperCase() === 'GET' || config.method.toUpperCase() === 'HEAD') {
      config.params = config.data
    } else {
      // config.data = qs.stringify(config.data)
    }
    const conf = { ...this.options, ...config }
    return this.instance.request(conf)
  }

  getAxios() {
    return this.instance
  }

  get(url, data) {
    return this.request({ url, data })
  }

  post(url, data) {
    return this.request({ url, data, method: 'POST' })
  }
}

export function createAxios(opt = {}) {
  return new Request({
    timeout: 60 * 1000,
    withToken: true,
    data: '',
    ...opt
  })
}

export default function baseRequest(options = {}) {
  const _request = createAxios(options)
  return ['post', 'put', 'patch', 'delete', 'get', 'head'].reduce((request, method) => {
    request[method] = (url, data = {}) => _request.request({ url, data, method })
    return request
  }, {})
}